var express = require('express');
var router = express.Router();
var request = require('request');

var CommonJS = require('../../../common/common');
var DBConfig = require('../../../db/dbconfig');
var mysql = require('mysql');
var pool = mysql.createPool(DBConfig.mysql2);


// 绑定手机号
router.get('/jkyx/bind_tel', function(req, res, next) {
	var param = req.query || req.params; 
	// 用户的openid
	var openid = param.openid || '';
//	console.log(openid);
	// 用户的手机号
	var tel = param.tel;
	// 验证码
	var varcode = param.varcode || '';
	// 获取客户端ip
	var ip = req.ip.replace(/::ffff:/, ''); 
	ip = '113.57.89.30';
    pool.getConnection(function(err, connection) {
		if(err){
			res.end(JSON.stringify({
     			msg: '数据库连接失败',
     			status:'101',
     		}));
		}
		connection.query(DBConfig.getVarcodeByAccount,[tel],function (err, results) {
			if (err){
				connection.release();
			  	res.end(JSON.stringify({
	     			msg: '数据库查询失败',
	     			status:'102',
	     			err: err
	     		}));
			}else{
				if (results.length == 0) { // 不存在验证码
					res.end(JSON.stringify({
	         			msg: '未查村到验证码记录!',
	         			status:'103',
	         		}));
				} else{
					var identify_code = results[0].identify_code;
					var create_time = results[0].create_time;
					// 验证码输入错误
					if (identify_code != varcode) {
						connection.release();
						res.end(JSON.stringify({
		         			msg: '验证码错误，请重新输入',
		         			status:'104',
		         			results: results
		         		}));
					} else{ // 验证码输入OK
						var timer = CommonJS.timestamp();
						var is_time_out = timer - create_time;
						if (is_time_out > CommonJS.time_out) { // 验证码 超过5  分钟 过期了
							connection.query(DBConfig.varCode_isOver,[tel],function (err, results) {
								connection.release();
								if (err){
								  	res.end(JSON.stringify({
						     			msg: '数据库查询失败',
						     			status:'105',
						     			err: err
						     		}));
								}else{
									res.end(JSON.stringify({
					         			msg: '验证码已过期',
					         			status:'106',
					         		}));
								}
							})
						} else{ // 验证码有效
							var taobaoIP = 'http://ip.taobao.com/service/getIpInfo.php?ip=' + ip;
							request(taobaoIP, function (error, response, body) {
								var provice = '';
								var city = '';
								var area = '';
					   			if (!error && response.statusCode == 200) {
					   				body = JSON.parse(body);
					   				provice = body.data.region || '';
					   				city = body.data.city || '';
					   				area = body.data.isp || '';
					   			}
					   			var ctDate = CommonJS.getNowFormatDate();
					   			connection.query(DBConfig.getAccountByAccount,[tel],function (err, results) {
									if (err){
									  	res.end(JSON.stringify({
							     			msg: '数据库查询失败',
							     			status:'106',
							     			err: err
							     		}));
									}else{
										// 数据库没有就注册
										if (results.length == 0) {
											connection.query(DBConfig.registerWithAccount,[tel,tel,tel,ctDate,tel,3,ip,provice,city,area,ctDate,tel],function (err, results) {
												connection.release();
												if (err){
												  	res.end(JSON.stringify({
										     			msg: '数据库查询失败',
										     			status:'106',
										     			err: err
										     		}));
												}else{
													// 获取个人信息
													var userInfo = results[3][0];
													userInfo.balance = userInfo.balance / 100;
													res.end(JSON.stringify({
									         			msg: '绑定成功',
									         			status:'100',
									         			userInfo: userInfo
									         		}));
												}
											})
										} else{ // 数据库有 就更新数据
											connection.query(DBConfig.updateOpenid,[tel,openid,tel,tel,1,ip,provice,city,area,ctDate,tel],function (err, results) {
												connection.release();
												if (err){
												  	res.end(JSON.stringify({
										     			msg: '数据库查询失败',
										     			status:'106',
										     			err: err
										     		}));
												}else{
													// 获取个人信息
													var userInfo = results[3][0];
													userInfo.balance = userInfo.balance / 100;
													res.end(JSON.stringify({
									         			msg: '绑定成功',
									         			status:'100',
									         			userInfo: userInfo
									         		}));
												}
											})
										}
									}
								})
					   		})
						}
					}	
				}
			}
		})
	})
});

module.exports = router;
